
'use strict';

/**
	Part of Zombie Navigator
	Copyright © 2015  Zombie Navigator Developers
	
	@file
	@module
	@license AGPL-3.0+
*/


/* Addon SDK dependencies */
const _sdkSimplePrefs = require('sdk/simple-prefs');


/* Exported APIs */

/**
	@public
*/
const openPreferences = (readable, writable) => {
	const sdkSimplePrefs = _sdkSimplePrefs;
	
	writable = Array.from(writable);
	readable = Array.from(readable);
	
	const validatePrefValue = value => {
		if ('string' == typeof value) {
			value = '' + value;
		} else if ('number' == typeof value) {
			value = 1 * value;
		} else if ('boolean' == typeof value) {
			value = !!value;
		} else {
			throw new TypeError('Invalid preference value\'s type');
		}
		
		return value;
	};
	
	const validatePrefName = name => {
		if ('string' == typeof name) {
			return '' + name;
		}
		
		throw new TypeError('Name must be a string');
	};
	
	return new Proxy(Object.create(null), {
		get (o, name) {
			name = validatePrefName(name);
			
			if (0 > readable.indexOf(name)) {
				return void(0); // undefined
			}
			
			let value = sdkSimplePrefs.prefs[name];
			
			return validatePrefValue(value);
		}
		,
		has (o, name) {
			name = validatePrefName(name);
			
			if (0 > readable.indexOf(name)) {
				return false;
			}
			
			return name in sdkSimplePrefs.prefs;
		}
		,
		set (o, name, value) {
			name = validatePrefName(name);
			
			if (0 > writable.indexOf(name)) {
				throw new ReferenceError('No such preference item: cannot be set');
			}
			
			value = validatePrefValue(value);
			
			sdkSimplePrefs.prefs[name] = value;
			
			return true;
		}
	});
};


/* Exports */
exports.openPreferences = openPreferences;


// vim: ts=4 noet ai

